package vn.cuhanh.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.apache.http.HttpException;
import org.json.JSONException;
import org.json.JSONObject;

import vn.cuhanh.ConfirmSharing;
import vn.cuhanh.GameDetailActivity;
import vn.cuhanh.MainActivity;
import vn.cuhanh.R;
import vn.cuhanh.ShareActivity;
import vn.cuhanh.bean.ShareInfo;
import vn.cuhanh.sdk.ZingMeSDK;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.android.zing.ZME_Base;
import com.android.zing.ZME_Error;
import com.android.zing.api.ZME_ASyncGraphAPI.RequestListener;
import com.android.zing.api.ZME_Social;

public class ShareZingMe {
	
	public static Runnable shareSuccessCallback;
	public static Runnable shareFailCallback;
	public static Runnable shareCancelCallback;
	public static RequestListener requestListener;
	public static Context ctx;
	public static String lastPostId = "";
	
	public static void showShareUnknownFail(final Context ctx) {
		((Activity)ctx).runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				HelperFunc.showSimpleAlertDialog(ctx, ctx.getResources().getString(R.string.shareFailTitle), 
						ctx.getResources().getString(R.string.shareFailMessage), 
						ctx.getResources().getString(R.string.bt_ok_title), null, null, null, true);
			}
		});
	}
	
	public static void shareZingMe(final Context ctx, final ShareInfo shareInfo, Runnable successCallback, Runnable failCallback, Runnable cancelCallback) {
		ShareZingMe.ctx = ctx;
		shareSuccessCallback = successCallback;
		shareFailCallback = failCallback;
		shareCancelCallback = cancelCallback;
		LoginHelper loginHelper = LoginHelper.getInstance();
		if(loginHelper.isSessionExpired(ctx)) {
			loginHelper.requestZingMeLogin(ctx, new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					shareZingMe(ctx, shareInfo, shareSuccessCallback, shareFailCallback, shareCancelCallback);
				}
			});
			return;
		}
		ZME_Base zme = ZingMeSDK.getInstance().getZME_Base();
		ZME_Social zme_social = new ZME_Social(zme);
		zme_social.share(shareInfo.getName(), shareInfo.getTitle(), shareInfo.getDescription() + ShareActivity.getDownloadRef(ctx), shareInfo.getUrlImg(), 
				shareInfo.getLink(), shareInfo.getState(), getRequestListener()); 
	}
	
	public static void confirmSharingZingMe(final Context ctx, final ShareInfo shareInfo) {
		ZME_Base zme = ZingMeSDK.getInstance().getZME_Base();
		if(zme.isSessionValid(ctx)) {
			String zingMeName = MainActivity.userAccount != null ? MainActivity.userAccount.getZingMeName() : MainActivity.username;
			Intent intent = new Intent(ctx, ConfirmSharing.class);
			intent.putExtra("vn.cuhanh.ConfirmSharing.name", shareInfo.getName());
			intent.putExtra("vn.cuhanh.ConfirmSharing.description", shareInfo.getDescription() + ShareActivity.getDownloadRef(ctx));
			intent.putExtra("vn.cuhanh.ConfirmSharing.imageUrl", shareInfo.getUrlImg());
			intent.putExtra("vn.cuhanh.ConfirmSharing.destination", ShareActivity.DESTINATION_ZING_ME);
			intent.putExtra("vn.cuhanh.ConfirmSharing.userDisplayName", zingMeName);
			intent.putExtra("vn.cuhanh.ConfirmSharing.userName", MainActivity.username);
			((Activity)ctx).startActivityForResult(intent, ShareActivity.CONFIRM_SHARING_REQUEST_CODE);
			return;
		}
		requestLoginAndShareZingMe(ctx, shareInfo);
	}
	
	public static void requestLoginAndShareZingMe(final Context ctx, final ShareInfo shareInfo) {
		final LoginHelper loginHelper = LoginHelper.getInstance();
		loginHelper.requestZingMeLogin(ctx, new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				GameDetailActivity.forceRestartOnResume = true;
				confirmSharingZingMe(ctx, shareInfo);
			}
		});
	}
	
	public static String getRandomFunnyPhrase(Context ctx) {
		String[] strings = ctx.getResources().getStringArray(R.array.funny_phrase);
		if(strings == null || strings.length == 0) {
			return "";
		}
		int index = (int) Math.round(Math.random() * (strings.length - 1));
		if(index >= 0 && index < strings.length) {
			return strings[index];
		}
		HelperFunc.readStackTrace(new Exception("Index out of bound: " + index));
		return "";
	}
	
	public static RequestListener getRequestListener(){
		if(requestListener != null) {
			return requestListener;
		}
		return new RequestListener() {
			
			@Override
			public void onZmeError(ZME_Error e) {
				// TODO Auto-generated method stub
//				SharingAisSharingProcessing = false;
//				progress.dismiss();
				if(shareFailCallback != null) {
					shareFailCallback.run();
				}
				HelperFunc.readStackTrace(e);
			}
			
			@Override
			public void onProgressStarted(long lengthOfFile) {
				// TODO Auto-generated method stub
				Log.d("zingmeshare", "progress started: " + String.valueOf(lengthOfFile));
			}
			@Override
			public void onProgressFinished() {
				// TODO Auto-generated method stub
				Log.d("zingmeshare", "finished");
//				isSharingProcessing = false;
//				progress.dismiss();
			}
			@Override
			public void onProgressError(String errorMsg) {
				// TODO Auto-generated method stub
				Log.d("zingmeshare", "onProgressError: " + errorMsg);
				if(shareFailCallback != null) {
					shareFailCallback.run();
				}
			}
			@Override
			public int onProgress(int percent) {
				// TODO Auto-generated method stub
				Log.d("zingmeshare", "progress: " + percent);
				return 0;
			}
			@Override
			public void onNullPointerException(NullPointerException e) {
				// TODO Auto-generated method stub
				if(shareFailCallback != null) {
					shareFailCallback.run();
				}
				HelperFunc.readStackTrace(e);
			}
			@Override
			public void onMalformedURLException(MalformedURLException e) {
				// TODO Auto-generated method stub
				if(shareFailCallback != null) {
					shareFailCallback.run();
				}
				HelperFunc.readStackTrace(e);
			}
			@Override
			public void onJsonException(JSONException e) {
				// TODO Auto-generated method stub
				if(shareFailCallback != null) {
					shareFailCallback.run();
				}
				e.printStackTrace();
			}
			@Override
			public void onIOException(IOException e) {
				// TODO Auto-generated method stub
				//no network: java.net.SocketTimeoutException
				if(shareFailCallback != null) {
					shareFailCallback.run();
				}
				HelperFunc.readStackTrace(e);
			}
			@Override
			public void onHttpException(HttpException e) {
				// TODO Auto-generated method stub
				if(shareFailCallback != null) {
					shareFailCallback.run();
				}
				HelperFunc.readStackTrace(e);
			}
			@Override
			public void onFileNotFoundException(FileNotFoundException e) {
				// TODO Auto-generated method stub
				if(shareFailCallback != null) {
					shareFailCallback.run();
				}
				HelperFunc.readStackTrace(e);
			}
			@Override
			public void onComplete(Object data) {
				// TODO Auto-generated method stub
				lastPostId = "";
				try {
					lastPostId = ((JSONObject)data).getString("feedId");
				} catch (Exception e) {
					HelperFunc.readStackTrace(e);
				}
				if(shareSuccessCallback != null) {
					shareSuccessCallback.run();
				}
			}
			@Override
			public void onCancelUpload() {
				// TODO Auto-generated method stub
				if(shareCancelCallback != null) {
					shareCancelCallback.run();
				}
			}
		};
	}
}
